// 创建悬浮提示框
function createFloatingBox() {
    const box = document.createElement('div');
    box.id = 'collector-status';
    box.style.cssText = `
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: rgba(0, 0, 0, 0.8);
        color: white;
        padding: 15px 20px;
        border-radius: 5px;
        z-index: 9999;
        font-size: 14px;
    `;
    document.body.appendChild(box);
    return box;
}

// 延时函数
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

async function autoScroll() {
    const statusBox = createFloatingBox();
    let lastHeight = document.documentElement.scrollHeight;
    let noNewDataCount = 0;
    let previousItemCount = 0;
    
    while (true) {
        const items = document.getElementsByClassName('feeds-item-wrap--rGdH_KoF');
        statusBox.textContent = `正在滚动页面... 已找到 ${items.length} 条数据`;
        
        window.scrollTo(0, document.documentElement.scrollHeight);
        await delay(2000); // 等待2秒加载新内容
        
        let newHeight = document.documentElement.scrollHeight;
        if (newHeight === lastHeight && items.length === previousItemCount) {
            noNewDataCount++;
            if (noNewDataCount >= 3) { // 连续3次没有新数据，认为到底了
                break;
            }
        } else {
            noNewDataCount = 0;
        }
        
        lastHeight = newHeight;
        previousItemCount = items.length;
    }
}

async function collectData() {
    await autoScroll();
    
    const items = document.getElementsByClassName('feeds-item-wrap--rGdH_KoF');
    console.log('找到元素数量:', items.length);
    
    const itemsData = [];
    const statusBox = document.getElementById('collector-status');
    
    for (let i = 0; i < items.length; i++) {
        const item = items[i];
        try {
            const title = item.querySelector('.row1-wrap-title--qIlOySTh')?.textContent?.trim() || '';
            const link = item.getAttribute('href') || '';
            const quantity = item.querySelector('.text--MaM9Cmdn')?.textContent || '';
            const priceInteger = item.querySelector('.number--NKh1vXWM')?.textContent || '';
            const priceDecimal = item.querySelector('.decimal--lSAcITCN')?.textContent || '';
            const price = priceInteger + priceDecimal;

            statusBox.textContent = `正在采集第 ${i + 1}/${items.length} 个商品的详细信息...`;

            // 打开新标签页采集好评率
            let rating = '';
            if (link) {
                await delay(1000); // 每次采集间隔1秒
                const response = await chrome.runtime.sendMessage({
                    type: 'OPEN_AND_COLLECT',
                    url: link
                });
                rating = response?.rating || '';
            }

            itemsData.push({
                title,
                link,
                quantity,
                price,
                rating
            });

        } catch (error) {
            console.error('处理元素时出错:', error);
        }
    }

    if (statusBox) {
        statusBox.textContent = '数据采集完成，准备下载...';
        await delay(1000);
        statusBox.remove();
    }

    return itemsData;
}

// 执行采集并发送结果
(async () => {
    try {
        const data = await collectData();
        if (data && data.length > 0) {
            chrome.runtime.sendMessage({ 
                type: 'COLLECTED_DATA', 
                data: data 
            }, (response) => {
                if (chrome.runtime.lastError) {
                    console.error('发送消息失败:', chrome.runtime.lastError);
                } else {
                    console.log('数据发送成功');
                }
            });
        } else {
            console.error('未采集到数据');
        }
    } catch (error) {
        console.error('采集过程出错:', error);
    }
})();